let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: '',         
    id: 0,          
    article: {},
    articles: [],
    pageNum: 1,
    pageSize: 3,   
    isLoading: false,
    userId: null
  },
  getIntensiveArticle() {
    wx.request({
      url: this.data.url + 'article/byPage',
      method: "GET",
      data: {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      },
      success: (resp) => {
        this.setData({
          articles: resp.data.data.list
        })
        console.log(resp.data.data.list)
      }
    })
  },
  /**
   * 获取文章详情
   */
  getArticle() {
    wx.request({
      url: this.data.url + 'article/' + this.data.id,
      success: (resp) => {
        this.setData({
          article: resp.data.data || {}
        })
        console.log('文章详情数据：', resp.data.data);
      },
      fail: (err) => {
        console.error('获取文章详情失败：', err);
        wx.showToast({
          title: '加载文章失败',
          icon: 'none'
        });
      }
    })
  },

  /**
   * 处理点赞/取消点赞
   */
  handleLike() {
    if (this.data.isLoading) return;
    const userId = this.data.userId;
    if (!userId || isNaN(Number(userId))) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    this.setData({ isLoading: true });

    const { article, id, url } = this.data;
    const isCurrentlyLiked = article.isLiked || false;
    const status = isCurrentlyLiked ? '取消点赞' : '点赞';
    const requestUrl = `${url}article?id=${id}&status=${encodeURIComponent(status)}&userId=${Number(userId)}`;

    wx.request({
      url: requestUrl,
      method: 'PUT', 
      success: (res) => {
        if (res.statusCode !== 200) {
          wx.showToast({
            title: `请求错误：${res.statusCode}`,
            icon: 'none'
          });
          return;
        }

        if (res.data.code === 200) {
          let newLikeCount = (article.likeCount || 0);
          newLikeCount = isCurrentlyLiked ? newLikeCount - 1 : newLikeCount + 1;
          this.setData({
            article: {
              ...article,
              likeCount: newLikeCount,
              isLiked: !isCurrentlyLiked
            }
          });

          wx.showToast({
            title: isCurrentlyLiked ? '取消点赞成功' : '点赞成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('点赞请求失败：', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('当前文章ID：', options.id);
    const userInfo = wx.getStorageSync('user') || {};
    console.log('缓存中的用户信息：', userInfo); 
    const userId = userInfo.id || null;

    // 初始化页面数据
    this.setData({
      url: app.globalData.url, 
      id: options.id,       
      userId: userId        
    });

    // 加载文章详情
    this.getArticle();
    this.getIntensiveArticle()
  },

  /**
   * 其他生命周期函数
   */
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})